package com.platform.modules.mall.activityV2.rule;

import com.platform.common.exception.BusinessException;
import com.platform.modules.mall.activityV2.entity.ParticipantBo;
import com.platform.modules.mall.activityV2.entity.WinnerBo;
import com.platform.modules.mall.entity.MallGoodsEntity;
import com.platform.modules.mall.entity.MallGoodsToActivityEntity;
import com.platform.modules.mall.service.MallGoodsService;
import com.platform.modules.mall.service.MallGoodsToActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Component("directGoodsRule")
public class DirectGoodsRule implements RuleInterface{

    @Autowired
    private MallGoodsService mallGoodsService;

    @Autowired
    private MallGoodsToActivityService mallGoodsToActivityService;
    /**
     * 1.查看商品id是否在活动关联商品当中
     * 2.减扣关联商品
     * 3.减扣商品库存
     * 4.构建返回对象
     * @param bo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public WinnerBo execute(ParticipantBo bo) {
        List<MallGoodsToActivityEntity> list = bo.getList();

        MallGoodsToActivityEntity entity = mallGoodsToActivityService.getByActivityIdAndGoodsId(bo.getActivityId(),bo.getGoodsId());
        if (entity==null){
            throw new BusinessException("该商品不在活动中");
        }

        boolean bool = mallGoodsToActivityService.deductionNumber(entity.getId(), bo.getRequestNum());
        if (!bool){
            throw new BusinessException("该商品在此活动中库存不足");
        }

        MallGoodsEntity goods = mallGoodsService.shoppingNotException(entity.getGoodsId(), bo.getRequestNum(), null);
        if (goods==null){
            throw new BusinessException("该商品的库存不足");
        }

        WinnerBo winnerBo =new WinnerBo();
        winnerBo.setGoodsEntity(goods);
        winnerBo.setNum(bo.getNum()-bo.getRequestNum());
        winnerBo.setList(list);
        return winnerBo;
    }
}
